import React, { useEffect, useState, memo } from 'react';
import { Dropdown, MenuProps, Space, Divider, Tooltip, App } from 'antd';
import { RightOutlined, LeftOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { useMatches, useLocation } from 'react-router-dom';
import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useUserInfo, useUserActions, useUserState } from '@/store/userStore';
import { DropdownProps } from 'antd/es/dropdown/dropdown';
import { useConfig } from '@/store/configStore';
import { useRoleManage } from '@/store/roleManageStore';
import { useMenuItems } from './MenuList';
import { useRouter } from '@/router/hooks';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import { logout } from '@/pages/auth/authUtils';
import {
  useHomePage,
  useConfigActions,
  useInitializeData,
  useDatasetFlag,
  useApiFlag,
} from '@/store/configStore';
import { useNavigate } from 'react-router-dom';
// import { calc } from 'antd/es/theme/internal';
import AdviceModal from '@/pages/components/modal/AdviceModal';
import LicenseModal from '@/pages/components/modal/LicenseModal';
import LicenseConfirmModal from '@/pages/components/modal/LicenseConfirm';
import { useOrchestrationStore } from '@/store/orchestrationStore';
const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
const licenseFlag = LICENSEFLAG === 'true' ? true : false;

import appService from '@/api/services/appService';

import UserRoleDisplay from './UserRoleDisplay';

import './styles/home-menu.css';

import { useTourActions, useIsTourStart, useIsUserClick } from '@/store/tourStore';
import { useTranslation } from 'react-i18next';
import { generateUUID } from '@/utils/common';

interface MenuProp {
  key?: string;
  label?: React.ReactNode;
  icon?: React.ReactNode;
  classname?: string;
  divider?: boolean;
  istooltip?: boolean;
  onClick?: () => void;
  child?: MenuProp[];
}

function RouterMenu() {
  const { message } = App.useApp();
  const { t } = useTranslation();

  const matches = useMatches();
  const { isPc } = useWindowWidth();
  const [currentMenu, setCurrentMenu] = useState<MenuProps['items']>(undefined);
  const location = useLocation();

  const [showMenu, setShowMenu] = useState(true);
  const router = useRouter();

  const { isGuest, isAdmin } = useUserState();
  const datasetFlag = useDatasetFlag();
  const apiFlag = useApiFlag();

  const { id, share_id } = useConfig();
  const { setLinkParams, fetchInitialInfo } = useConfigActions();
  const initializeData = useInitializeData();

  const [isHovered, setIsHovered] = useState(false);
  const [activeKey, setActiveKey] = useState('');
  const [logoutVisible, setLogoutVisible] = useState(false);
  const [showAdvice, setShowAdvice] = useState(false);
  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);

  const [actIcon, setActIcon] = useState('');
  const [inputValue, setInputValue] = useState('');

  const { setIsTourStart, setIsTourGuide } = useTourActions();
  const isUserClick = useIsUserClick();

  // 获取编排页面状态
  const { isInOrchestrationPage, setIsInOrchestrationPage } = useOrchestrationStore();


  const [isActivateConfirmModalOpen, setIsActivateConfirmModalOpen] = useState(false);


  useEffect(() => {
    if (isUserClick) {
      setActiveKey('5');
    } else {
      setActiveKey('');
    }
  }, [isUserClick]);

  useEffect(() => {
    if (!id || Object.keys(initializeData).length === 0) {
      fetchInitialInfo();
    }
  }, []);

  // 检测当前路由，判断是否在编排页面
  useEffect(() => {
    const isOrchestrationPath = location.pathname.includes('/apps/orchestration');
    setIsInOrchestrationPage(isOrchestrationPath);
  }, [location.pathname, setIsInOrchestrationPage]);

  const handleLogoutCancel = () => {
    setLogoutVisible(false);
  };

  const handleAdviceCancel = () => {
    setActIcon('');
    setInputValue('');
    setShowAdvice(false);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const handleAdviceConfirm = async (actId: string, text: string) => {
    console.log('===============', id, text);

    if (id) {
      appService
        .surveySubmit(id, {
          content: {
            title: t('page.homePage.postTitleText'),
            feedback: text,
            score: actId,
          },
        })
        .then((res) => {
          console.log(res);
          message.success(t('page.homePage.submitSuccess'));
          setActIcon('');
          setInputValue('');
          setShowAdvice(false);
        });
    }
  };

  const handleLogoutConfirm = async () => {
    setLogoutVisible(false);
    logout(router);
  };

  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setActiveKey('');

    setIsHovered(false);
  };

  const handleMouseEnteritem = (item: MenuProp) => {
    if (item.key) {
      setActiveKey(item.key);
    }
  };

  const handleMouseLeaveitem = (item: MenuProp) => {
    // setActiveKey('');
  };

  const handleShowMenu = () => {
    showMenu ? setShowMenu(false) : setShowMenu(true);
  };

  const navigate = useNavigate();
  const appMenus: MenuProp[] = [
    {
      key: '4',
      label: t('page.homePage.functionalCenter'),
      classname: 'jr-step-4',
      divider: true,
      icon: 'home-widgets',
      onClick: () => {
        router.push('/management');
      },
    },
  ];


  const licenseMenus: MenuProp[] = [
    {
      key: 'license',
      label: t('page.homePage.appActivation'),
      divider: true,
      icon: (
        <SvgIcon
          icon="home-license"
          size={30}
          style={{
            padding: '3px',
            color: '#515152',
          }}
        />
      ),
      onClick: () => {
        setIsLicenseModalOpen(true)
      },
    },
  ];

  const homeMenu1: MenuProp[] = [
    {
      key: '2',
      label: t('page.homePage.createConversation'),
      divider: false,
      icon: 'home-new',
      onClick: () => {
        // setActiveKey('2');
        if (isInOrchestrationPage) {
          // 在编排页面内打开
          if (id && share_id) {
            setLinkParams({ id, share_id, chat_id: '' });
            const event = new CustomEvent('orchestration-content-change', {
              detail: { type: 'chat', id, share_id }
            });
            window.dispatchEvent(event);
          }
        } else {
          router.push(`/homepage`);
        }
      },
    },
    {
      key: '3',
      label: t('page.homePage.historyConversation'),
      divider: false,
      icon: 'home-history',
      onClick: () => {
        if (licenseFlag && !initializeData?.is_license_valid) {
          setIsActivateConfirmModalOpen(true)
          return
        }

        // setActiveKey('3');
        if (isInOrchestrationPage) {
          // 在编排页面内打开
          const event = new CustomEvent('orchestration-content-change', {
            detail: { type: 'history' }
          });
          window.dispatchEvent(event);
        } else {
          router.push('/history');
        }
      },
    },
  ]

  const homeMenu: MenuProp[] = [
    {
      key: '1',
      label: t('page.homePage.homePage'),
      divider: true,
      icon: 'home-home',
      onClick: () => {
        router.push(`/homepage`);
        // setActiveMenu('1');
      },
    },
    {
      key: '2',
      label: t('page.homePage.createConversation'),
      divider: false,
      icon: 'home-new',
      onClick: () => {
        if (licenseFlag && !initializeData?.is_license_valid) {
          setIsActivateConfirmModalOpen(true)
          return
        }
        if (id && share_id) {
          setLinkParams({ id, share_id, chat_id: '' });
          navigate(`/apps/chat/${id}/${share_id}`);
        }
      },
    },
    {
      key: '3',
      label: t('page.homePage.historyConversation'),
      divider: false,
      icon: 'home-history',
      onClick: () => {
        if (licenseFlag && !initializeData?.is_license_valid) {
          setIsActivateConfirmModalOpen(true)
          return
        }
        router.push('/history');
      },
    },
    ...(isGuest || !(datasetFlag || apiFlag || isAdmin) ? [] : appMenus),
    {
      key: '5',
      label: t('page.homePage.userCenter'),
      istooltip: true,
      classname: 'jr-step-3-mobile',
      divider: false,
      icon: 'home-user',
      onClick: () => {
        // router.push(`/apps/manage/${id}`);
      },

      child: [
        {
          key: '7',
          // label: username,
          label: <UserRoleDisplay activeKey={activeKey} key={generateUUID()} />,
          divider: true,
          icon: (
            <SvgIcon
              icon="home-user-user"
              size={30}
              style={{
                padding: '3px',
                color: '#515152',
              }}
            />
          ),
          onClick: () => { },
        },
        {
          key: '9',
          label: <div className="jr-step-4-mobile">{t('page.homePage.userFeedback')}</div>,
          divider: true,
          // classname: 'jr-step-4-mobile',
          icon: (
            <SvgIcon
              icon="home-user-email"
              size={30}
              style={{
                padding: '3px',
                color: '#515152',
              }}
            />
          ),
          onClick: () => {
            if (licenseFlag && !initializeData?.is_license_valid) {
              setIsActivateConfirmModalOpen(true)
              return
            }
            setInputValue('');
            setActIcon('');
            setShowAdvice(true);
          },
        },
        {
          key: '10',
          label: t('page.homePage.beginnerGuide'),
          divider: true,
          icon: (
            <SvgIcon
              icon="home-help"
              size={30}
              style={{
                padding: '3px',
                color: '#515152',
              }}
            />
          ),
          onClick: () => {
            if (licenseFlag && !initializeData?.is_license_valid) {
              setIsActivateConfirmModalOpen(true)
              return
            }
            // setIsTourStart(true);
            setIsTourStart(false);
            setIsTourGuide(true);
            router.push('/homepage');
          },
        },
        ...((isAdmin && licenseFlag) ? licenseMenus : []),
        {
          key: '11',
          label: t('page.homePage.logOut'),
          divider: true,
          icon: (
            <SvgIcon
              icon="home-user-exit"
              size={30}
              style={{
                padding: '3px',
                color: '#515152',
              }}
            />
          ),
          onClick: () => {
            setLogoutVisible(true);
          },
        },
      ],
    },
  ];

  // 根据是否在编排页面选择不同的菜单
  const currentMenuList = isInOrchestrationPage ? homeMenu1 : homeMenu;

  return (
    <div
      onMouseEnter={isInOrchestrationPage ? () => { } : handleMouseEnter}
      onMouseLeave={isInOrchestrationPage ? () => { } : handleMouseLeave}
      style={{
        // width: '50px',
        display: 'flex',
        position: 'absolute',
        top: isPc ? 'calc(50% - 120px)' : '60px',
        // border: '1px solid green',
        marginLeft: '20px',
        // overflow: 'hidden',
        transform: showMenu ? 'translateX(0)' : 'translateX(calc(-100% + 15px))', // 控制滑动位置
        transition: 'transform 0.3s ease-in-out', // 添加过渡效果
        zIndex: 100,
      }}
    >
      {/* <Dropdown
        trigger={isPc ? ['click'] : ['click']}
        className="w-[140px]"
        dropdownRender={dropdownRender}
        menu={{
          items: isAdmin ? itemList : itemList2,
        }}
      >
        <Space>
          <RightOutlined style={{ fontSize: '20px', color: 'gray' }} onClick={handleShowMenu} />
        </Space>
      </Dropdown> */}

      <div
        className="jr-step-2"
        style={{
          border: '1px solid #fff',
          // position: 'absolute',
          // marginTop: '-117px',
          borderRadius: '10px',
          backgroundColor: '#fff',
          boxShadow: '0px 1px 5px 0px rgba(64,80,152,0.16)',
          marginRight: '10px',
          cursor: 'pointer',
        }}
      >
        {currentMenuList.map((item) => {
          return (
            <div
              key={item.key}
              style={{ width: '100%', position: 'relative' }}
              onMouseEnter={() => {
                !isInOrchestrationPage && handleMouseEnteritem(item);
              }}
              onMouseLeave={() => !isInOrchestrationPage && handleMouseLeaveitem(item)}
              className={item?.classname || ''}
            >
              {item?.istooltip ? (
                <div style={{ padding: '10px' }} onClick={item.onClick}>
                  {/* {item.icon} */}
                  <SvgIcon
                    icon={typeof item.icon === 'string' ? item.icon : ''}
                    size={30}
                    style={{
                      // padding: '3px',
                      color: activeKey == item.key ? '#6E35FF' : 'grey',
                      // color: 'grey',
                    }}
                  />
                </div>
              ) : (
                <Tooltip title={item.label} placement="right">
                  <div style={{ padding: '10px' }} onClick={item.onClick}>
                    {/* {item.icon} */}
                    <SvgIcon
                      icon={typeof item.icon === 'string' ? item.icon : ''}
                      size={30}
                      style={{
                        // padding: '3px',
                        color: activeKey == item.key ? '#6E35FF' : 'grey',
                        // color: 'grey',
                      }}
                    />
                  </div>
                </Tooltip>
              )}

              <div
                style={{
                  position: 'absolute',
                  left: '60px',
                  top: '0px',
                  background: ' #FFFFFF',
                  boxShadow: '0px 1px 5px 0px rgba(64,80,152,0.16)',
                  borderRadius: '12px',
                  border: '1px solid #FFFFFF',
                  display: activeKey === item.key ? 'block' : 'none',
                }}
              >
                {item?.child &&
                  item?.child.map((cld) => {
                    return (
                      <div
                        key={cld.key}
                        style={{
                          padding: '5px 10px',
                          display: 'flex',
                          width: '120px',
                          fontSize: '13px',
                          alignItems: 'center',
                        }}
                        onClick={cld.onClick}
                      >
                        <div style={{ marginRight: '6px' }}>{cld.icon}</div>
                        <div>{cld.label}</div>
                      </div>
                    );
                  })}
              </div>

              {item.divider && (
                <div style={{ width: '80%', marginLeft: '10%' }}>
                  <Divider style={{ borderColor: '#CECECE', margin: '0' }} />
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div
        style={{
          display: isPc ? 'block' : 'none',
          // border: '1px solid red',
          width: '30px',
        }}
      >
        <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center' }}>
          {showMenu ? (
            <>
              <div className={`layoutNavShow ${isHovered && 'layoutNav'}`} onClick={handleShowMenu}>
                <div className="layoutNavLine">
                  <div className="layoutNavLine0"></div>
                  <div className="layoutNavLine1"></div>
                </div>
              </div>
              {/* <SvgIcon
                onClick={handleShowMenu}
                style={{
                  fontSize: '20px',
                  scale: '1.5',
                  display: isHovered ? 'block' : 'none',
                }}
                icon={'mingcute--left-fill'}
                size={30}
                color="#c8c7d8"
              /> */}
            </>
          ) : (
            <>
              <div className={'layoutNavHide layoutNav'} onClick={handleShowMenu}>
                <div className="layoutNavLine">
                  <div className="layoutNavLine0"></div>
                  <div className="layoutNavLine1"></div>
                </div>
              </div>
              {/* <SvgIcon
                onClick={handleShowMenu}
                style={{
                  fontSize: '20px',
                  scale: '1.5',
                }}
                icon={'mingcute--right-fill'}
                size={30}
                color="#c8c7d8"
              /> */}
            </>
          )}
        </div>
      </div>

      <DeleteConfirmModal
        visible={logoutVisible}
        text={t('page.homePage.sureOut')}
        onCancel={handleLogoutCancel}
        onConfirm={handleLogoutConfirm}
        onConfirmText={t('page.homePage.logOut')}
      />

      <AdviceModal
        visible={showAdvice}
        actIcon={actIcon}
        setActIcon={setActIcon}
        inputValue={inputValue}
        setInputValue={setInputValue}
        onCancel={handleAdviceCancel}
        onConfirm={handleAdviceConfirm}
      />

      <LicenseModal
        visible={isLicenseModalOpen}
        onCancel={handleLicenseCancel}
      />

      <LicenseConfirmModal
        visible={isActivateConfirmModalOpen}
        onCancel={() => { setIsActivateConfirmModalOpen(false) }}
      />

    </div>
  );
}

export default memo(RouterMenu);
